from appium.webdriver.common.appiumby import AppiumBy
from base.base_page import BasePage
from utils.logger import Logger
import time


class SingleOrderPage(BasePage):
    logger = Logger().get_logger()

    # 页面元素定位
    # 客户编码绑定相关
    GO_BIND_BUTTON = (AppiumBy.XPATH, "//android.widget.TextView[@text='去绑定']")
    CLOSE_TIP_BUTTON = (AppiumBy.XPATH, "//android.widget.TextView[@text='X']")

    # 收件人信息相关
    RECEIVER_NAME_INPUT = (
    AppiumBy.XPATH, "//android.widget.EditText[contains(@hint, '收件人') and @resource-id='...']")
    RECEIVER_PHONE_INPUT = (AppiumBy.XPATH, "//android.widget.EditText[contains(@hint, '电话') and @resource-id='...']")
    RECEIVER_ADDRESS_INPUT = (
    AppiumBy.XPATH, "//android.widget.EditText[contains(@hint, '地址') and @resource-id='...']")

    # 寄件方式相关
    SHIPMENT_METHOD_BUTTON = (
    AppiumBy.XPATH, "//android.widget.TextView[@text='请选择' and contains(@resource-id, 'shipment_method')]")
    SHIPMENT_METHOD_OPTIONS = (AppiumBy.XPATH, "//android.widget.ListView//android.widget.TextView")

    # 货好时间相关
    GOODS_READY_TIME_BUTTON = (
    AppiumBy.XPATH, "//android.widget.TextView[@text='请选择' and contains(@resource-id, 'goods_time')]")
    # 假设时间选择器元素
    TIME_PICKER_DAY = (AppiumBy.XPATH, "//android.widget.NumberPicker[@resource-id='...day']")
    TIME_PICKER_HOUR = (AppiumBy.XPATH, "//android.widget.NumberPicker[@resource-id='...hour']")
    TIME_PICKER_MINUTE = (AppiumBy.XPATH, "//android.widget.NumberPicker[@resource-id='...minute']")
    TIME_PICKER_CONFIRM = (AppiumBy.XPATH, "//android.widget.Button[@text='确定']")

    # 付款方式相关
    PAYMENT_METHOD_BUTTON = (
    AppiumBy.XPATH, "//android.widget.TextView[@text='请选择' and contains(@resource-id, 'payment')]")
    PAYMENT_METHOD_OPTIONS = (AppiumBy.XPATH, "//android.widget.ListView//android.widget.TextView")

    # 货物信息相关
    GOODS_INFO_INPUT = (AppiumBy.XPATH, "//android.widget.EditText[contains(@hint, '货物') and @resource-id='...']")

    # 服务方式相关
    SERVICE_METHOD_BUTTON = (
    AppiumBy.XPATH, "//android.widget.TextView[@text='请选择' and contains(@resource-id, 'service')]")
    SERVICE_METHOD_OPTIONS = (AppiumBy.XPATH, "//android.widget.ListView//android.widget.TextView")

    # 保价声明相关
    INSURANCE_DECLARATION_BUTTON = (AppiumBy.XPATH, "//android.widget.TextView[@text='保价声明']")
    INSURANCE_AMOUNT_INPUT = (
    AppiumBy.XPATH, "//android.widget.EditText[contains(@hint, '保价') and @resource-id='...']")
    INSURANCE_CONFIRM_BUTTON = (AppiumBy.XPATH, "//android.widget.TextView[@text='确定']")

    # 电子运单条款
    WAYBILL_TERMS_CHECKBOX = (AppiumBy.XPATH, "//android.widget.CheckBox[contains(@resource-id, 'terms')]")

    # 下单按钮
    PLACE_ORDER_BUTTON = (AppiumBy.XPATH, "//android.widget.TextView[@text='下单' and @resource-id='...']")

    # 订单提交成功标识（根据实际页面调整）
    ORDER_SUCCESS_TEXT = (AppiumBy.XPATH, "//android.widget.TextView[@text='订单提交成功' or @text='查看订单详情']")

    # ---------------------- 操作方法 ----------------------
    def click_close_tip(self):
        """关闭客户编码绑定提示"""
        if self.is_element_exist(self.CLOSE_TIP_BUTTON):
            self.click(self.CLOSE_TIP_BUTTON)
            self.logger.info("已关闭客户编码绑定提示")
        else:
            self.logger.info("未检测到客户编码绑定提示")

    def input_receiver_name(self, name):
        """输入收件人姓名"""
        self.send_keys(self.RECEIVER_NAME_INPUT, name)
        self.logger.info(f"已输入收件人姓名：{name}")

    def input_receiver_phone(self, phone):
        """输入收件人电话"""
        self.send_keys(self.RECEIVER_PHONE_INPUT, phone)
        self.logger.info(f"已输入收件人电话：{phone}")

    def input_receiver_address(self, address):
        """输入收件人地址"""
        self.send_keys(self.RECEIVER_ADDRESS_INPUT, address)
        self.logger.info(f"已输入收件人地址：{address}")

    def select_shipment_method(self, method):
        """选择寄件方式"""
        self.click(self.SHIPMENT_METHOD_BUTTON)
        self.logger.info(f"准备选择寄件方式：{method}")
        self._select_from_dropdown(self.SHIPMENT_METHOD_OPTIONS, method)

    def select_payment_method(self, method):
        """选择付款方式"""
        self.click(self.PAYMENT_METHOD_BUTTON)
        self.logger.info(f"准备选择付款方式：{method}")
        self._select_from_dropdown(self.PAYMENT_METHOD_OPTIONS, method)

    def select_service_method(self, method="标准服务"):
        """选择服务方式（默认标准服务）"""
        self.click(self.SERVICE_METHOD_BUTTON)
        self.logger.info(f"准备选择服务方式：{method}")
        self._select_from_dropdown(self.SERVICE_METHOD_OPTIONS, method)

    def input_goods_info(self, info):
        """输入货物信息"""
        self.send_keys(self.GOODS_INFO_INPUT, info)
        self.logger.info(f"已输入货物信息：{info}")

    def select_goods_ready_time(self, days=1, hour=10, minute=30):
        """选择货好时间（默认明天10:30）"""
        self.click(self.GOODS_READY_TIME_BUTTON)
        self.logger.info(f"准备选择货好时间：{days}天后 {hour}:{minute}")

        # 选择日期（假设当前日期+days天）
        self._set_number_picker_value(self.TIME_PICKER_DAY, (int(time.strftime("%d")) + days) % 31)

        # 选择时间
        self._set_number_picker_value(self.TIME_PICKER_HOUR, hour)
        self._set_number_picker_value(self.TIME_PICKER_MINUTE, minute)

        self.click(self.TIME_PICKER_CONFIRM)
        self.logger.info("已选择货好时间")

    def click_insurance_declaration(self):
        """点击保价声明"""
        self.click(self.INSURANCE_DECLARATION_BUTTON)
        self.logger.info("已点击保价声明")

    def set_insurance_amount(self, amount):
        """设置保价金额"""
        self.send_keys(self.INSURANCE_AMOUNT_INPUT, amount)
        self.logger.info(f"已设置保价金额：{amount}")

    def click_confirm_insurance(self):
        """确认保价声明"""
        self.click(self.INSURANCE_CONFIRM_BUTTON)
        self.logger.info("已确认保价声明")

    def check_waybill_terms(self):
        """勾选电子运单条款"""
        if not self.is_element_selected(self.WAYBILL_TERMS_CHECKBOX):
            self.click(self.WAYBILL_TERMS_CHECKBOX)
        self.logger.info("已勾选电子运单条款")

    def click_place_order(self):
        """点击下单按钮"""
        self.click(self.PLACE_ORDER_BUTTON)
        self.logger.info("已点击下单按钮")
        # 等待页面跳转
        time.sleep(2)

    def is_order_success(self):
        """验证订单是否提交成功"""
        result = self.is_element_exist(self.ORDER_SUCCESS_TEXT, timeout=10)
        self.logger.info(f"订单提交结果：{'成功' if result else '失败'}")
        return result

    # ---------------------- 私有辅助方法 ----------------------
    def _select_from_dropdown(self, dropdown_elements, option_text):
        """从下拉列表中选择指定选项"""
        options = self.find_elements(dropdown_elements)
        for option in options:
            if option_text in option.text:
                option.click()
                self.logger.info(f"已选择：{option_text}")
                return
        raise ValueError(f"未找到选项：{option_text}，可用选项：{[o.text for o in options]}")

    def _set_number_picker_value(self, picker_locator, target_value):
        """设置数字选择器的值"""
        picker = self.find_element(picker_locator)
        current_value = int(picker.text)

        # 向上或向下滚动选择目标值
        if current_value < target_value:
            for _ in range(target_value - current_value):
                picker.click()  # 假设点击为增加
        elif current_value > target_value:
            for _ in range(current_value - target_value):
                picker.click()  # 假设点击为减少
        self.logger.info(f"已设置选择器值为：{target_value}")